#ifdef defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif

#define TCP_SERVER_ADDR {{&server}}
#define TCP_SERVER_PORT {{&port}}
#ifndef AP_CONFIG
String UID = {{&clientId}};
#endif
#define MAX_PACKETSIZE 512
#define KEEPALIVEATIME 30*1000
WiFiClient TCPclient;
String TcpClient_Buff = "";
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;
unsigned long preTCPStartTick = 0;
bool preTCPConnected = false;
bool subFlag = false;
void doWiFiTick();
void doTCPClientTick();
void sendtoTCPServer(String p);

void subTopic(String topic) {
  String tcpTemp = "";
  tcpTemp = "cmd=1&uid="+UID+"&topic="+topic+"\r\n";
  Serial.println(tcpTemp);
  sendtoTCPServer(tcpTemp);
  tcpTemp="";
  Serial.print("sub topic:");
  Serial.println(topic);
}

void doWiFiTick() {
  static bool taskStarted = false;
  static uint32_t lastWiFiCheckTick = 0;
  if (WiFi.status() != WL_CONNECTED) {
    taskStarted = false;
    if (millis() - lastWiFiCheckTick > 1000) {
      lastWiFiCheckTick = millis();
      #ifdef ESP32
      WiFi.begin();
      #endif
    }
  } else {
    if (taskStarted == false) {
      taskStarted = true;
      Serial.print("Get IP Address: ");
      Serial.println(WiFi.localIP());
      startTCPClient();
    }
  }
}

void sendtoTCPServer(String p) {
  if (!TCPclient.connected()) {
    Serial.println("Client is not readly");
    return;
  }
  TCPclient.print(p);
  preHeartTick = millis(); //心跳计时开始，需要每隔60秒发送一次数据
}

void startTCPClient() {
  if (TCPclient.connect(TCP_SERVER_ADDR, TCP_SERVER_PORT)) {
    Serial.print("Connected to server:");
    Serial.println(TCP_SERVER_ADDR);  
    subFlag = true;
    preHeartTick = millis();
    TCPclient.setNoDelay(true);
  } else {
    Serial.print("Failed connected to server:");
    Serial.println(TCP_SERVER_ADDR);
    #ifdef ESP32
    TCPclient.stop();
    #else
    TCPclient.stopAll();
    #endif
    preTCPConnected = false;
  }
  preTCPStartTick = millis();
}